<template>
  <view class="uni-container">
    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title">采购单详情</view>
      </view>
    </view>

    <view class="uni-container">
      <uni-forms ref="form" :modelValue="formData" :label-width="100">
        <uni-forms-item label="采购单名称">
          <uni-easyinput type="text" :value="formData.title" :disabled="true" />
        </uni-forms-item>
        <uni-forms-item label="采购单编号">
          <uni-easyinput type="text" :value="formData.serial_number" :disabled="true" />
        </uni-forms-item>
        <uni-forms-item label="详细描述">
          <uni-easyinput type="textarea" :value="formData.description" :disabled="true" />
        </uni-forms-item>
        <uni-forms-item label="起始价格">
          <uni-easyinput type="digit" :value="formData.start_price" :disabled="true" />
        </uni-forms-item>
        <uni-forms-item label="报价截止时间">
          <uni-datetime-picker type="datetime" :value="formData.end_time" :disabled="true"></uni-datetime-picker>
        </uni-forms-item>
        <uni-forms-item label="状态">
          <text class="uni-forms-item-value">{{ statusText }}</text>
        </uni-forms-item>
        <uni-forms-item label="创建时间">
          <uni-dateformat :date="formData.create_time"></uni-dateformat>
        </uni-forms-item>
        <uni-forms-item v-if="formData.attachments && formData.attachments.length > 0" label="采购附件">
          <view v-for="(file, index) in formData.attachments" :key="index">
            <uni-link :href="file.url" :text="file.name"></uni-link>
          </view>
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 报价列表 -->
    <view class="bids-section" v-if="bids.length > 0">
      <view class="uni-header">
        <view class="uni-title">报价记录</view>
      </view>
      <!-- 采购方/管理员视图 -->
      <view v-if="isOwner" class="bids-list">
        <uni-table ref="table" border stripe emptyText="暂无更多数据">
          <uni-tr>
            <uni-th width="50" align="center">排名</uni-th>
            <uni-th width="150" align="center">供应商</uni-th>
            <uni-th align="center">报价金额</uni-th>
            <uni-th width="170" align="center">报价时间</uni-th>
          </uni-tr>
          <uni-tr v-for="(bid, index) in bids" :key="bid._id">
            <uni-td align="center">{{ index + 1 }}</uni-td>
            <uni-td align="center">{{ bid.supplier_user_id[0] ? bid.supplier_user_id[0].nickname || bid.supplier_user_id[0].username : '未知' }}</uni-td>
            <uni-td align="center">￥{{ bid.amount }}</uni-td>
            <uni-td align="center">
              <uni-dateformat :date="bid.timestamp"></uni-dateformat>
            </uni-td>
          </uni-tr>
        </uni-table>
      </view>
      <!-- 供应商视图 -->
      <view v-else-if="myBid" class="my-bid-info">
        <uni-card title="我的报价" :is-shadow="true">
          <view class="info-item">
            <text class="label">我的排名:</text>
            <text class="value rank">第 {{ myRank }} 名</text>
          </view>
          <view class="info-item">
            <text class="label">我的报价:</text>
            <text class="value amount">￥{{ myBid.amount }}</text>
          </view>
        </uni-card>
        <view class="tip">为保护隐私，其他供应商的报价信息已隐藏。</view>
      </view>
    </view>

    <view class="uni-button-group">
      <button v-if="!isOwner" type="primary" class="uni-button" @click="goToBidding" :disabled="formData.status !== 'bidding'">{{ myBid ? '修改报价' : '去报价' }}</button>
      <button class="uni-button" @click="navigateBack">返回</button>
    </view>
  </view>
</template>

<script>
  const db = uniCloud.database();
  const dbCollectionName = 'auctions';

  export default {
    data() {
      return {
        formData: {},
        currentUser: {},
        isOwner: false,
        bids: [],
        myBid: null,
        myRank: 0,
        statusOptions: {
          "bidding": "竞价中",
          "finished": "已结束"
        }
      }
    },
    computed: {
      statusText() {
        return this.statusOptions[this.formData.status] || this.formData.status;
      }
    },
    onLoad(e) {
      const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
      this.currentUser = {
        _id: userInfo._id,
        role: userInfo.role || []
      };

      if (e.id) {
        this.getDetail(e.id)
      }
    },
    methods: {
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            this.isOwner = this.currentUser._id === data.user_id || this.currentUser.role.includes('admin');
            this.getBids();
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      },
      getBids() {
        db.collection('bids,uni-id-users')
          .where(`auction_id == "${this.formData._id}"`)
          .field('amount,create_time,supplier_user_id{_id,nickname,username}')
          .orderBy('amount', 'asc')
          .orderBy('create_time', 'asc')
          .get()
          .then(res => {
            const bids = res.result.data;
            this.bids = bids;

            if (!this.isOwner) {
              const myBidIndex = bids.findIndex(bid => bid.supplier_user_id[0]._id === this.currentUser._id);
              if (myBidIndex !== -1) {
                this.myBid = bids[myBidIndex];
                this.myRank = myBidIndex + 1;
              }
            }
          }).catch(err => {
            console.error('获取报价列表失败', err);
          })
      },
      goToBidding() {
        uni.navigateTo({
          url: `/pages/bids/add?auctionId=${this.formData._id}`
        })
      },
      navigateBack() {
        uni.navigateBack()
      }
    }
  }
</script>

<style scoped>
.uni-container {
  padding: 15px;
}
.uni-header {
  margin-bottom: 15px;
}
.uni-title {
  font-size: 20px;
  font-weight: bold;
}
.uni-forms-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}
.uni-forms-item-label {
  width: 120px;
  font-weight: bold;
}
.uni-forms-item-value {
  flex: 1;
}
.bids-section {
  margin-top: 30px;
}
.my-bid-info {
  margin-top: 15px;
}
.info-item {
  display: flex;
  margin-bottom: 10px;
}
.label {
  font-weight: bold;
  margin-right: 10px;
}
.value.rank {
  color: #007AFF;
  font-weight: bold;
}
.value.amount {
  color: #ff4d4f;
  font-weight: bold;
}
.tip {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin-top: 15px;
}
.uni-button-group {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
</style>
